export async function streamOutput(url, payload, onProcess, onComplete) {
  try {
    const response = await fetch(url, {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify(payload),
    });

    if (!response.body) {
      throw new Error("Stream not supported");
    }

    if (!response.ok) {
      throw new Error(`API request failed with status ${response.status}`);
    }

    const reader = response.body.getReader();
    const decoder = new TextDecoder();
    let result = "";

    while (true) {
      const { done, value } = await reader.read();
      if (done) break;

      const chunk = decoder.decode(value, { stream: true });
      const lines = chunk.split("\n").filter((line) => line.trim() !== "");

      for (const line of lines) {
        const message = line.replace(/^data:/, "");
        if (message) {
          result += message;
          onProcess(result);
        }
      }
    }
  } catch (error) {
    console.error("Stream error:", error);
  } finally {
    onComplete();
  }
}
